// packageA/pages/repairList/repairList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
//去掉末尾的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '未接待', value: 3},
      {text: '未完成', value: 0},
      {text: '已完成', value: 1},
      {text: '再编辑', value: 2}
    ],
    valueState: -1,
    //接单人筛选
    optionReceive:[
      {text: '我接单的', value: 1},
      {text: '所有记录', value: 2},
    ],
    valueReceive: 2,
    //当前登录用户
    user:null,
    //用户权限
    authority:null,
    //更改接单人弹出框
    showReceive:false,
    //当前操作的数据
    currentObj:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //售后人员
    outDoorStaffs: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    let authority=app.globalData.authority;

    this.setData({
      user: user,
      authority: authority
    })
    
    //设置valueState（平台售后人员查未接待，其他查所有）
    if(authority.iot && authority.iot.afterSales && authority.iot.afterSales.afterBtn){
      this.setData({
        valueState: 3
      })
    }else{
      this.setData({
        valueState: -1
      })
    }

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('维修工单传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
    }

    //先获取售后人员，再获取维修工单列表
    this.getServicePersonal();  
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      selectFields: ["id", "orderNo", "equipmentNo", "depart", "project", "equipmentId", "receiver", "state", "costs","processingTime", "expirationTime", "serviceDetails", "businessType", "logistics", "repairInfo","completeDate", "closeOrderDate", "faultType", "processMode", "processResult", "trueFault", "pic","memberTypeName","remark","callRecord","dataAuthority","avgTravelCost","childrenAvgTravelCost","salesman","isShutDown","receptionTimeout","createDate","processingTimeout","equipmentObj","trackingInfo","imei"],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    //带有混合查询
    let complex=[];

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      //是否独立售后
      if(app.globalData.afterSaleSelf){
        dataObj.appId=app.globalData.myAppId;
      }else{
        dataObj.appId=[2,3,null];
      }
    }else{
        dataObj.appId=[2,3,null];
    }

    //单个设备的记录
    if(this.data.paramObj.equipmentId){
      dataObj.equipmentId=this.data.paramObj.equipmentId;
    }

    //设备编码或订单号模糊查询
    let val=this.data.searchValue.trim();
    if(val){
      complex.push({
        or: {
          equipmentNo: '%' +val+ '%',
          orderNo: '%' +val+ '%'
        }
      })
    }

    //筛选状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
    }

    //接单人
    if(this.data.valueReceive==1){
      dataObj['receiver.id']=this.data.user.id;
    }

    //从设备工时跳转来，查询departId
    if(this.data.paramObj.departId){
      dataObj['depart.id'] = this.data.paramObj.departId;
    }

    //混合查询
    dataObj.complex=complex;

    let param = {
      isAuth: true,
      className: 'afterSaleMaintainOrder',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.stateWord='未完成';
              item.stateClass='c-1';
              break;
            case 1:
              item.stateWord='已完成';
              item.stateClass='c-2';
              break;
            case 2:
              item.stateWord='再编辑';
              item.stateClass='c-3';
              break;
            case 3:
              item.stateWord='未接待';
              item.stateClass='c-4';
              break;
          }

          //业务类型
          if(item.businessType){
            switch(item.businessType){
              case 1:
                item.self_businessType='销售';
                break;
              case 2:
                item.self_businessType='租赁-授信';
                break;
              case 3:
                item.self_businessType='租赁-非授信';
                break;
              case 4:
                item.self_businessType='试机';
                break;
              case 5:
                item.self_businessType='存量改造';
                break;
            }
          }

          //工单费用
          let totalCost=0.0;
          if(item.logistics && item.logistics.length) {
            item.logistics.forEach(l => {
              totalCost += Number(l.freight);
              if(l.parts.length){
                l.parts.forEach(p => {
                  totalCost += Number(p.salePrice) * p.num;
                });
              }
            });
          }

          if(item.costs && item.costs.length) {
            item.costs.forEach(l => {
              totalCost += Number(l.cost);
            });
          }    

          //保留两位小数并去掉末尾的0
          item.totalCost=totalCost.toFixed(2).replace(regexp,'$1');

          //差旅单均摊费用保留两位小数并去掉末尾的0
          if(item.avgTravelCost){
            item.avgTravelCost=item.avgTravelCost.toFixed(2).replace(regexp,'$1');
          }

          //子差旅单均摊费用求和
          if(item.childrenAvgTravelCost && item.childrenAvgTravelCost.length){
            let num=0;
            item.childrenAvgTravelCost.forEach(item2 => {
              num+=item2.cost;
            });
            item.self_childrenTravel=num.toFixed(2).replace(regexp,'$1');
          }

          //处理接单时间类型
          if(item.processingTime && !item.processingTime.startsWith('0001-01')){
            item.self_processingTime=item.processingTime;
          }

          //处理闭单时间类型
          if(item.closeOrderDate && !item.closeOrderDate.startsWith('0001-01')){
            item.self_closeOrderDate=item.closeOrderDate;
          }

          //处理超时背景色
          if(item.state==3 && item.receptionTimeout){
            if(item.receptionTimeout.twentyFourHours){
              item.self_class='bg1';
            }else if(item.receptionTimeout.eightHours){
              item.self_class='bg2';
            }else if(item.receptionTimeout.fourHours){
              item.self_class='bg3';
            }else if(item.receptionTimeout.twoHours){
              item.self_class='bg4';
            }
          }

          if(item.state==0 && item.processingTimeout){
            if(item.processingTimeout.ninetySixHours){
              item.self_class='bg1';
            }else if(item.processingTimeout.seventyTwoHours){
              item.self_class='bg2';
            }else if(item.processingTimeout.fortyEightHours){
              item.self_class='bg3';
            }else if(item.processingTimeout.twentyFourHours){
              item.self_class='bg4';
            }
          }

          //是否显示接待按钮
          let user = app.globalData.userInfo;
          if(user.departObj[0].type==1 && item.depart && item.depart.id && item.project && item.project.id){
            let dutyMan = false;
            let outDoorStaffs = this.data.outDoorStaffs;
            let staff = null;
            
            //当前登录的售后人员的信息
            for(let i=0;i<outDoorStaffs.length;i++){
              if(outDoorStaffs[i].userId == user.id){
                staff = outDoorStaffs[i];
                break;
              }
            }
  
            //是否显示接待按钮            
            if(staff){
              //判断是否是此售后人员负责的公司和项目
              if(staff.dutyProject && staff.dutyProject.length){
                let dutyProject = staff.dutyProject;        
                for(let i=0;i<dutyProject.length;i++){
                  if(dutyProject[i].company == item.depart.id){
                    let project = dutyProject[i].project;
                    for(let j=0;j<project.length;j++){
                      if(project[j].id == item.project.id){
                        dutyMan = true;
                      }
                    }
                  }
                }
              }

              //判断是否是地区负责人
              if(staff.areaStr && staff.areaStr.length){
                if(item.equipmentObj && item.equipmentObj.length && item.equipmentObj[0].project && item.equipmentObj[0].project.length){
                  let area = item.equipmentObj[0].project[0].area;
                  if(area && area.province && area.province.name){
                    let pName = area.province.name;
                    let aa = staff.areaStr;
                    for(let i=0;i<aa.length;i++){
                      if(aa[i].name == pName){
                        dutyMan = true;
                        break;
                      }
                    }
                  }
                }
              }
            }
  
            item.self_dutyMan = dutyMan;
          }  
        });

        console.log('维修工单列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
  },

  //选择接单人
  onChangeReceive({detail}) {
    this.setData({
      valueReceive: detail
    })
    this.refreshListAndPage();
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转编辑(接待信息)
  goToEdit({currentTarget}){
    let detail = currentTarget.dataset.detail;
    let serviceRecord = currentTarget.dataset.servicerecord;

    let obj={
      id: detail.id,
      equipmentId: detail.equipmentId
    }

    //是否是已完成工单，跳转过后只显示服务记录
    if(serviceRecord){
      obj.showServiceRecord = true;
    }

    wx.navigateTo({
			url: "/packageA/pages/repairEdit/repairEdit?paramObj="+JSON.stringify(obj)
		})
  },

  //跳转物流
  goToLogistics(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo,
      //接单时间
      processingTime: detail.processingTime
    }

    wx.navigateTo({
			url: "/packageA/pages/repairLogistics/repairLogistics?paramObj="+JSON.stringify(obj)
		})
  },

  //添加报修
  goToAdd(){
    let obj={
      repairType: 216,
      equipmentId: this.data.paramObj.equipmentId
    }

    wx.navigateTo({
			url: "/pages/repairAdd/repairAdd?paramObj="+JSON.stringify(obj)
		})
  },

  //费用
  goToCosts(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentNo: detail.equipmentNo,
      //客户id和项目id，用于查询项目负责的售后人员
      departId: detail.depart.id,
      projectId: detail.project.id
    }

    wx.navigateTo({
			url: "/packageA/pages/repairCosts/repairCosts?paramObj="+JSON.stringify(obj)
		})
  },

  //详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      repairId: detail.id,
      equipmentId: detail.equipmentId,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/repairDetail/repairDetail?paramObj="+JSON.stringify(obj)
		})
  },

  //闭单
  onClose(e){
		let detail=e.currentTarget.dataset.detail;

    //接待信息必填
    if(detail.faultType && detail.processMode && detail.trueFault && detail.processResult){
    }else{
      Toast.fail('接待信息不完整');
      return;
    }

    Dialog.confirm({
      title: '确定关闭当前工单吗',
      message:'状态将更新为已完成',
      confirmButtonText:'关闭',
      cancelButtonText:'取消'
    }).then(() => {
      let param={
        id: detail.id
			}
			
			let param2={
				//设备id
				deviceld: detail.id,
				//设备编码
				device_number: detail.equipmentNo,
				//故障状态，编辑页面这里传1，完单时传0
				error_state: 0,
				//故障消息
				error_info: {}
			}			

      CommonService.closeMaintainOrder(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
					Toast.success('已关闭');
					
					//建发推送
					this.whichCompanyEquipment(detail.equipmentId, param2);

          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除当前工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        id: detail.id,
        equipmentId: detail.equipmentId,
      }

      CommonService.delMaintainOrder(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          this.refreshListAndPage();
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //拨打电话
  onCall(e){
    let userName=this.data.user.userName;
    let detail=e.currentTarget.dataset.detail;

    //打电话
    wx.makePhoneCall({
      phoneNumber: detail.repairInfo.phone
    })

    //保存点击记录
    let callRecord=[];
    if(detail.callRecord && detail.callRecord.length){
      callRecord=detail.callRecord;
    }
    callRecord.push({
      time: util.timeFormat(new Date()),
      name: userName
    });

    let param={
      className:'afterSaleMaintainOrder',
      data:{
        id: detail.id,
        callRecord: callRecord
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  //转单
  onChangeType(e){
    Dialog.confirm({
      title: '确定将当前工单转为耗材工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不转了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;
      let user = this.data.user;

      let param={
        id: detail.id,
        equipmentNo: detail.equipmentNo,
        equipmentId: detail.equipmentId,
        depart: detail.depart,
        project: detail.project,
        orderType: {
          id: 217,
          name: "耗材工单",
        },
        memberTypeName: detail.memberTypeName,
        repairMan: {
          name: detail.repairInfo.name,
          phone: detail.repairInfo.phone,
        },
        address: detail.repairInfo.address,
        repairDate: util.timeFormat(detail.repairInfo.date),
        createDate: util.timeFormat(detail.repairInfo.createDate),
        dataSource: 2,
        pic: detail.repairInfo.pic,
        repairQuestion: detail.repairInfo.question,
        businessType: detail.businessType,
        state: 0,
        appId: [app.globalData.myAppId],
        dataAuthority: detail.dataAuthority,
        //请求源
        requestSource: app.globalData.domainName,
        //创建人
        createUser:{
          id: user.id,
          name: user.userName
        },
        //物联网编码
        imei: detail.imei ? detail.imei : ''
      }

      //业务员
      if(detail.salesman){
        param.salesman=detail.salesman;
      }

      //地区和省市区
      let projectArea = {};
      let addressArea1 = {};
      if(detail.repairInfo.addressArea && detail.repairInfo.addressArea.length){
        detail.repairInfo.addressArea.forEach(a=>{
          if (a.code.indexOf('0000') > -1) {
            projectArea = a;
          }
        });
        addressArea1 = detail.repairInfo.addressArea;
      }
      param.area = projectArea;
      param.addressArea = addressArea1;

      // console.log(param);
      // return;

      CommonService.changeToConsumable(param).then(res=>{
        if (res.data.data.success == true){
          Dialog.confirm({
            title: '操作成功',
            confirmButtonText:'查看耗材工单',
            cancelButtonText:'留在本页'
          }).then(() => {
            //跳转到售后记录
            wx.reLaunch({
              url: '/packageA/pages/consumableList/consumableList'
            })
          }).catch(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          });

        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

   //显示更改接单人员
   onShowReceive(e){
    this.setData({
      showReceive: true,
      currentObj: e.currentTarget.dataset.detail
    })
  },

  //隐藏更改接单人员
  onCloseReceive(){
    this.setData({
      showReceive: false
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //接单人
    if(field=='receiver'){
      this.setData({
        selectTitle: '接单人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: ''
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //接单人
    if(selectField=='receiver'){
      obj='currentObj.receiver';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //接单人
    if(selectField=='receiver'){
      this.getStaffList();
    }
  },

  //查询人员
  getStaffList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'servicePersonal',
      data: {
        searchAll: true,
        type: 33,
        selectFields: ['serviceName','telephone','userId']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.serviceName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.serviceName,
            id: item.userId,
            obj: {
              id: item.userId,
              name: item.serviceName,
              phone: item.telephone
            }
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //确定更改接单人
  onConfirmReceive(){
    let current=this.data.currentObj;

    //接单人在u_service_personal表中有userId的才能转，否则转完了无法编辑
    if(current.receiver.id){
      this.onCloseReceive();

      Dialog.confirm({
        title: '确定更改接单人吗',
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(() => {
        let param={
          className:'afterSaleMaintainOrder',
          data:{
            id: current.id,
            receiver: current.receiver
          }
        }

        CommonService.goSave(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true){
            //刷新列表和页码
            this.refreshListAndPage();
          }else{
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          Toast.fail('操作失败');
        })

      }).catch(() => {
      });
    }else{
      Toast.fail('无法转单，人员信息缺失，请到管理后台维护');
    }
  },

  //跳转设备列表
  goToEquipment({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let arr=[detail.equipmentNo];
    wx.navigateTo({
      url: "/pages/equipmentList/equipmentList?equipmentNoArr="+JSON.stringify(arr)
    })
  },

  //接待
  onReceive({currentTarget}){
    Dialog.confirm({
      title: '确定接待当前工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {
      let detail = currentTarget.dataset.detail;
      let user = this.data.user;
      let param={
        id: detail.id,
        userId: user.id
      }

      CommonService.receivingMaintainOrder(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          //刷新列表和页码
          this.refreshListAndPage();
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //获取售后人员
  getServicePersonal(){
    let param = {
      isAuth: true, 
      className: 'servicePersonal',
      data: {
        searchAll: true,
        type: 33,
        selectFields: ['id','serviceName','type','telephone','departId','userId','partnerCode','dutyProject','areaStr']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result = res.data.data.result;        
        this.setData({
          outDoorStaffs: result
        })
      }

      //获取列表数据
      this.getList();

    }).catch((error) => {
    })
  },

  //生成配件采购单
  onPurchaseOrder({currentTarget}){
    let detail=currentTarget.dataset.detail;

    //物流配件必填
    if(detail.logistics && detail.logistics.length){
      //接待信息必填
      if(detail.faultType && detail.processMode && detail.trueFault && detail.processResult){
      }else{
        Toast.fail('接待信息不完整');
        return;
      }

      //如果全是旧件退回    
      let flag = detail.logistics.every(item=>{
        return item.returned;
      });

      if(flag){
        Toast.fail('均为退回配件');
        return;
      }else{
        //把不是旧件退回的找出来
        let arr = [];
        detail.logistics.forEach(item=>{
          if(!item.returned){
            arr.push(item);
          }
        });

        //省市区取值： p:省 c:市 d:区
        let p='', c='', d='';
        if(detail.repairInfo.addressArea && detail.repairInfo.addressArea.length) {
          let addressInfo = detail.repairInfo.addressArea;
          if (addressInfo[0].name) {
            p = addressInfo[0].name
          }
          if (addressInfo[1].name) {
            c = addressInfo[1].name
          }
          if (addressInfo[2].name) {
            d = addressInfo[2].name
          }
        }
        
        //省市区必填
        if(p && c && d){
        }else{
          Toast.fail('省市区为空');
          return;
        }

        //参数
        let param={
          //原维修工单保留数据
          maintainOrder: {
            //工单ID
            id: detail.id,
            //工单号
            orderNo: detail.orderNo,
            //设备编码
            equipmentNo: detail.equipmentNo,
            //机构
            depart: detail.depart,
            //项目
            project: detail.project
          },
          //收货信息
          goodsReceivingInfo: {
            //收货人
            name: detail.repairInfo.name,
            //收货人电话
            phone: detail.repairInfo.phone,
            //省市区
            cities: p +' '+ c +' '+ d,
            //详细街道地址
            address: detail.repairInfo.address
          },
          //业务员
          salesman: detail.salesman,
          //接待人员
          serviceStaff: {
            id: detail.receiver.id,
            name: detail.receiver.name
          },
          //物流配件信息
          logistics: arr
        }

        //确认收货信息        
        Dialog.confirm({
          title: '核对收货信息',
          message: '请核对收货信息是否正确？此信息关系到采购单，请谨慎操作。\n\n收货地区：' + param.goodsReceivingInfo.cities + '\n地址：' + param.goodsReceivingInfo.address+ '\n收货人：' + param.goodsReceivingInfo.name + '\n联系方式：' + param.goodsReceivingInfo.phone,
          messageAlign: 'left',
          confirmButtonText:'确定',
          cancelButtonText:'取消'
        }).then(() => {
          CommonService.autoGenerationM(param).then(res => {
            if(res.data.data.success){
              Toast.success('创建配件采购单成功');

              setTimeout(() => {
                this.refreshListAndPage();
              }, 1000);
            }else{
              Toast.fail(res.data.data.message);
            }
          }).catch((error) => {
          })
    
        }).catch(() => {
        });
      }
    }else{
      Toast.fail('未填写配件物流信息');
    }
  },

  //配件更换明细
  goToPartDetail({currentTarget}){
    let detail = currentTarget.dataset.detail;

    let obj={
      equipmentId: detail.equipmentId,
      equipmentNo: detail.equipmentNo
    }

    wx.navigateTo({
			url: "/packageA/pages/repairPartDetailList/repairPartDetailList?paramObj="+JSON.stringify(obj)
		})
  },

  //删除采购单
  delConsumablePurchaseOrder(detail){
    let param={
      id: detail.id, 
      orderNo: detail.orderNo, 
      type: 2
    }

    CommonService.delPurchaseOrder(param).then(res=>{
    }).catch((error) => {
    })
  },

  //跳转上传接待图片
  goToUploadImg({currentTarget}){
    let detail = currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
			url: "/packageA/pages/repairUploadImg/repairUploadImg?paramObj="+JSON.stringify(obj)
		})
	},
	
	//建发消息推送zyx
	whichCompanyEquipment(equipmentId,errorInfo){
		//发送通知的公司
		let sendNoticeCompany = [100114, 100540,100866];

		//先查询设备，有可能和报修时不在一个客户下，所以查一下
		let param={
      isAuth: false,
      className: 'equipment',
      data:{
        id: equipmentId,
        selectFields:['id', 'imei', 'equipmentNo', 'memberId']
      }
		}
		
		CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
				let result = res.data.data.result[0];	

				//是否推送
				let sendNotice = false,CS = false,JF = false;

				for (let i = 0; i < sendNoticeCompany.length; i++) {
					if (result.memberId === sendNoticeCompany[i]) {
						//测试
						CS = sendNoticeCompany[i] === 100114;
						//建发 
						JF = sendNoticeCompany[i] === 100540 || sendNoticeCompany[i] === 100866;
						sendNotice = true;
					}
				}

				if (sendNotice && JF) {
					//获取客户token
					this.getCustomerToken(errorInfo);
				}	
      }
    }).catch((error) => {
    })
	},

	//获取客户token
	getCustomerToken(paramInfo){
		CommonService.jianfaToken().then(res=>{
			if(res.data.data && res.data.data.result){
				let token = res.data.data.result;

				//推送信息
				this.pushMessagesToCustomers(token,paramInfo);
			}      
    }).catch((error) => {
    })
	},

	//推送信息
	pushMessagesToCustomers(token,paramInfo){
		let data = {
			token: token,
			deviceId: paramInfo.deviceld,
			deviceNumber: paramInfo.device_number,
			errorState: paramInfo.error_state,
			faultType: '',
			trueFault: '',
			createDate: '',
		}

		if (paramInfo.error_state === 1) {
			data.faultType = paramInfo.error_info.faultType.name;
			data.trueFault = paramInfo.error_info.trueFault;
			data.createDate = paramInfo.error_info.createDate;
		}	

		//消息推送
		CommonService.jianfaSend(data).then(res=>{
    }).catch((error) => {
    })
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})